import 'package:flutter/material.dart';
import 'package:pocket/core/http/axios_http_client.dart';
import 'package:pocket/core/http/dio_http_client.dart';

import '../http/models/gitcode_user.dart';
import '../services/user_service.dart';

class UserProfilePage extends StatefulWidget {
  final String username;

  const UserProfilePage({super.key, required this.username});

  @override
  _UserProfilePageState createState() => _UserProfilePageState();
}

class _UserProfilePageState extends State<UserProfilePage> {
  final ApiService _userService = ApiService(new AxiosHttpClient());
  GitCodeUser? _user;
  List<dynamic> _repos = [];
  bool _isLoading = true;
  String _error = '';

  @override
  void initState() {
    super.initState();
    _userService.initialize();
    _loadUserData();
  }

  Future<void> _loadUserData() async {
    setState(() {
      _isLoading = true;
      _error = '';
    });

    try {
      final results = await Future.wait([
        _userService.getUserInfo(widget.username),
        _userService.getUserRepos(widget.username),
      ]);

      final user = results[0] as GitCodeUser;
      final repos = results[1] as List<dynamic>;

      setState(() {
        _user = user;
        _repos = repos;
      });
    } catch (e) {
      setState(() {
        _error = e.toString();
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GitCode 用户信息'),
        backgroundColor: Colors.blue,
        actions: [
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: _loadUserData,
          ),
        ],
      ),
      body: _isLoading
          ? Center(child: CircularProgressIndicator())
          : _error.isNotEmpty
          ? Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.red),
            SizedBox(height: 16),
            Text(
              '加载失败',
              style: TextStyle(fontSize: 18, color: Colors.red),
            ),
            SizedBox(height: 8),
            Text(_error),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _loadUserData,
              child: Text('重试'),
            ),
          ],
        ),
      )
          : _user == null
          ? Center(child: Text('用户不存在'))
          : SingleChildScrollView(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户基本信息卡片
            Card(
              elevation: 4,
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Row(
                  children: [
                    CircleAvatar(
                      radius: 40,
                      backgroundColor: Colors.grey[300],
                      backgroundImage: _user!.avatarUrl != null
                          ? NetworkImage(_user!.avatarUrl!)
                          : null,
                      child: _user!.avatarUrl == null
                          ? Icon(Icons.person, size: 40)
                          : null,
                    ),
                    SizedBox(width: 16),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            _user!.name,
                            style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          SizedBox(height: 4),
                          Text(
                            '@${_user!.login}',
                            style: TextStyle(
                              color: Colors.grey,
                            ),
                          ),
                          SizedBox(height: 8),
                          if (_user!.bio != null)
                            Text(
                              _user!.bio!,
                              style: TextStyle(
                                fontStyle: FontStyle.italic,
                              ),
                            ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 16),

            // 统计信息
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                _buildStatItem('仓库', _user!.publicRepos),
                _buildStatItem('粉丝', _user!.followers),
                _buildStatItem('关注', _user!.following),
              ],
            ),

            SizedBox(height: 24),

            // 仓库列表
            Text(
              '最新仓库',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: 12),
            ..._repos.map((repo) => _buildRepoItem(repo)),
          ],
        ),
      ),
    );
  }

  Widget _buildStatItem(String label, int count) {
    return Column(
      children: [
        Text(
          count.toString(),
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.blue,
          ),
        ),
        SizedBox(height: 4),
        Text(
          label,
          style: TextStyle(
            color: Colors.grey,
          ),
        ),
      ],
    );
  }

  Widget _buildRepoItem(Map<String, dynamic> repo) {
    return Card(
      margin: EdgeInsets.only(bottom: 8),
      child: ListTile(
        leading: Icon(Icons.folder, color: Colors.blue),
        title: Text(
          repo['name'] ?? '未知仓库',
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        subtitle: repo['description'] != null
            ? Text(repo['description'])
            : null,
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.star, size: 16, color: Colors.amber),
            SizedBox(width: 4),
            Text('${repo['stargazers_count'] ?? 0}'),
          ],
        ),
      ),
    );
  }
}